
//  Created by 莫瑞权 on 2022/4/24.
//  Copyright © 2022 Talkfun. All rights reserved.
//

import UIKit

class TFHorizontalQuestionView: UIView, UITableViewDelegate, UITableViewDataSource {
    
    let view = UIButton()
    
    @objc public var isShow:Bool = false
    
    @objc public let closeBtn = UIButton()
    @objc public let titlelab = UILabel()
    @objc public let tableView = UITableView()
    
    @objc public let nodataView = UIView()
    @objc public let noLabel = UILabel()
    @objc public let noImg = UIImageView()
    @objc public let dataSource = NSMutableArray()
    @objc func viewClick()
    {
        
    }
    func showView(_ isShow:Bool)
    {
        let viewW:CGFloat = 375
        var viewX = self.frame.width
        
        if isShow {
            viewX = self.frame.width - viewW
        }
        
        if isShow {
            self.view.frame = CGRect(x: self.frame.width, y: 0, width: 375, height: self.frame.height)
        }
        self.layoutSubviewsUI()
        if (self.superview != nil) {
            self.superview?.addSubview(self)
        }
        self.isHidden = false
        UIView.animate(withDuration: 0.5, delay: 0.0, options: UIView.AnimationOptions.allowAnimatedContent) {
            self.view.frame = CGRect(x: viewX, y: 0, width: viewW, height: self.frame.height)
        } completion: { Bool in
            
            if isShow == false {
                self.isHidden = true
            }
        }
        
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.isHidden = true
        
        self.view.backgroundColor = UIColor.white
        self.addSubview(self.view)
        self.view.addTarget(self, action: #selector(viewClick), for: .touchUpInside)
        
        
        self.titlelab.text = "提问记录"
        self.titlelab.textAlignment = .center
        self.titlelab.textColor = UIColor(red: 48/255.0, green: 51/255.0, blue: 75/255.0, alpha: 1)
        self.titlelab.font = UIFont.PingFang(size: 18)
        self.view.addSubview(self.titlelab)
        
        self.closeBtn.setImage(UIImage.init(named: "HTLive.bundle/close_gray"), for: .normal)
        self.closeBtn.backgroundColor = UIColor.clear
        self.view.addSubview(self.closeBtn)
        
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView.separatorStyle = .none
        self.view.addSubview(self.tableView)
        
        self.view.addSubview(self.nodataView)
        
        self.noImg.image = UIImage.init(named: "HTLive.bundle/Default page_ask")
        self.nodataView.addSubview(self.noImg)
        
        self.noLabel.text = "暂无提问"
        self.noLabel.font = UIFont.PingFang(size: 16)
        self.noLabel.textColor = UIColor(red: 20/255.0, green: 23/255.0, blue: 26/255.0, alpha: 1)

        self.noLabel.textAlignment = .center
        self.nodataView.addSubview(self.noLabel)
        
        self.tableView.register(TFQuestionCell.self, forCellReuseIdentifier: "TFQuestionCell")
       
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
     func layoutSubviewsUI()
    {
      
        self.titlelab.frame = CGRect(x: (self.view.frame.size.width-100)/2.0, y: 20, width: 100, height: 30)
       
        self.closeBtn.frame = CGRect(x: self.view.frame.size.width-10-30, y: 20, width: 30, height: 30)
      
        self.nodataView.frame = CGRect(x: 0, y: 70, width: self.view.frame.size.width, height: self.view.frame.size.height-70)
        
        self.tableView.frame = CGRect(x: 0, y: 70, width: self.view.frame.size.width, height: self.view.frame.size.height-70)
        
        self.noImg.frame = CGRect(x: (self.nodataView.frame.size.width-200)/2.0, y: (self.nodataView.frame.size.height-150)/2.0, width: 200, height: 150)
        self.noLabel.frame = CGRect(x: 0, y: self.noImg.frame.maxY-40, width: self.nodataView.frame.size.width, height: 22)
       
    }
    /**回复提问*/
    @objc public func pePly_Question(model:TFQuestionData)
    {
        
        let copyArray = NSMutableArray.init(array: self.dataSource)
        
        var answer:Bool = false
        
        for i in stride(from: 0, to: copyArray.count ,by: 1) {
       
            let obj = copyArray[i] as! TFQuestionData
            //本地自己的提问中是否查询到
            
             if (obj.qid == model.qid) {
                 answer = true
                 self.dataSource.replaceObject(at: i, with: model)
                
                // [self.dataSource replaceObjectAtIndex:i withObject:model];
                 
            
                break;
            }
            
        }
        
        //新增新的
        if (answer==false) {
            self.dataSource.add(model)

            
        }
        self.tableView.reloadData()
        
        if (self.dataSource.count > 0) {
            self.nodataView.isHidden = true
        } else {
            self.nodataView.isHidden = false
        }
    }

    /**接收提问*/
    
    @objc public func update_Question(model:TFQuestionData)

    {
        for i in stride(from: 0, to: self.dataSource.count ,by: 1) {

            let obj = self.dataSource[i] as! TFQuestionData
            if (obj.qid == model.qid) {
              return;
          }
        }
        self.dataSource.add(model)

        self.tableView.reloadData()

        
        let indexpath = NSIndexPath.init(row: self.dataSource.count - 1, section: 0)
        
        self.tableView.scrollToRow(at: indexpath as IndexPath, at: .bottom, animated: true)
     
        
        if (self.dataSource.count > 0) {
            self.nodataView.isHidden = true
        } else {
            self.nodataView.isHidden = false
        }
    }

    /**删除*/
    
    @objc public func remove_Question(model:TFQuestionData)
 
    {
        
        for i in stride(from: 0, to: self.dataSource.count ,by: 1) {
//        for (int i=0; i<self.dataSource.count; i++) {
            let obj = self.dataSource[i] as! TFQuestionData
//            if ([obj isKindOfClass:[TFQuestionData class]]) {
//                TFQuestionData *data = obj;
            if (obj.qid == model.qid) {
                
                
                let deleteQuestionID:NSString = model.deleteQuestionID as NSString
                    if (deleteQuestionID.length > 0) {
                        
                        for i in stride(from: 0, to: obj.answer.count ,by: 1) {
//                        for (TFQuestionAnswer * answer in obj.answer) {
                            
                            let answer = self.dataSource[i] as! TFQuestionAnswer
                            if (answer.qid == model.deleteQuestionID) {
//                                [data.answer removeObject:answer];
                                obj.answer.remove(model)
                                break;
                            }
                        }
                    } else {
//                        [self.dataSource removeObject:data];
                        self.dataSource.remove(model)
                        break;
                    }
                }
//            }
        }
        self.tableView.reloadData()
//        [self.tableView reloadData];
        if (self.dataSource.count > 0) {
            self.nodataView.isHidden = true;
        } else {
            self.nodataView.isHidden = false;
        }
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return self.dataSource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "TFQuestionCell") as! TFQuestionCell

        cell.cellwidth = self.frame.size.width;
        cell.isOrientationLandscape = true
        cell.selectionStyle = .none;
        cell.isQuestion = true;
        cell.isChatArea = false;
        
        let model = self.dataSource[indexPath.row] as! TFQuestionData
        cell.model = model;
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

        let  model = self.dataSource[indexPath.row] as! TFQuestionData
        
        let height = self.getHeight(model: model)
        
        return height;
    }
    
    func getHeight(model:TFQuestionData)->CGFloat
  
    {
        let nickname = model.nickname + " "
        let  str11 = nickname + model.content
        
        let AttributedString = NSMutableAttributedString.init(string: str11)
        let size = TalkfunSharedTools.getSizeLabel(labelString: AttributedString, labelWidth:self.tableView.frame.width-35-16-12-16, labelfont: UIFont.PingFang(size: 14))
        
        
        
        if (model.answer.count > 0) {
            var height:CGFloat = 0
            var anserwidth:CGFloat = 0
            for i in stride(from: 0, to: model.answer.count ,by: 1) {

                let answer = model.answer[i] as! TFQuestionAnswer
 
                
                let str = answer.nickname + answer.content
                let AttributedString = NSMutableAttributedString.init(string: str)
                let attr14: [NSAttributedString.Key : Any] = [.font: UIFont.PingFang(size: 14) as Any,]
                AttributedString.addAttributes(attr14, range: NSRange(location: 0, length: AttributedString.length))


                let attch = NSTextAttachment()
                attch.bounds = CGRect(x: 0, y: -3, width: 27, height: 15)
                
                let imageStr = NSAttributedString.init(attachment: attch)
                AttributedString.insert(imageStr, at: (answer.nickname as NSString).length+1)
        
                AttributedString.insert(NSAttributedString.init(string: " "), at: (answer.nickname as NSString).length+2)
                AttributedString.addAttribute(NSAttributedString.Key.kern, value: (5), range: NSRange(location: (answer.nickname as NSString).length+2, length: 1))
                
                let answersize = TalkfunSharedTools.getSizeLabel(labelString: AttributedString, labelWidth:self.tableView.frame.width-35-16-12-16, labelfont: UIFont.PingFang(size: 14))

                
                height = height+answersize.height+10
              
               //取最大值
                if answersize.width>anserwidth {
                    anserwidth = answersize.width
                }


            }

            return size.height+10+1+height+4;


        } else {
            
            return size.height+4+12;
           
        }

        
     
    }
    
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.showView(false)
    }
}
